package com.yj.auto.core.web.system.service;

import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.SqlPara;
import com.yj.auto.core.base.annotation.Service;
import com.yj.auto.core.base.model.QueryModel;
import com.yj.auto.core.jfinal.base.BaseService;
import com.yj.auto.core.web.system.model.Schedule;
import com.yj.auto.helper.ScheduleHelper;
import com.yj.auto.utils.QuartzUtil;

/**
 * Schedule 管理 描述：
 */
@Service(name = "scheduleSrv")
public class ScheduleService extends BaseService<Schedule> {

	private static final Log logger = Log.getLog(ScheduleService.class);

	public static final String SQL_LIST = "system.schedule.list";

	public static final Schedule dao = new Schedule().dao();

	@Override
	public Schedule getDao() {
		return dao;
	}

	@Override
	public SqlPara getListSqlPara(QueryModel query) {
		if (StrKit.isBlank(query.getOrderby())) {
			query.setOrderby("sort");
		}
		return getSqlPara(SQL_LIST, query);
	}

	// 根据任务代码查询
	public Schedule getByCode(String code) {
		String sql = "select * from t_sys_schedule where code=?";
		return dao.findFirst(sql, code);
	}

	public List<Schedule> all() {
		QueryModel query = new QueryModel();
		query.setOrderby("sort");
		query.setState(QuartzUtil.JOB_STATE_NONE);
		return getDao().find(getListSqlPara(query));
	}

	public boolean save(Schedule model) {
		boolean success = model.save();
		if (success) {
			ScheduleHelper.addJob(model);
		}
		return success;
	}

	public boolean update(Schedule model) {
		boolean success = model.update();
		if (success) {
			ScheduleHelper.modifyJobTime(model);
		}
		return success;
	}

	public boolean delete(Integer... ids) {
		if (null == ids || ids.length < 1)
			return false;
		for (Integer id : ids) {
			ScheduleHelper.removeJob(get(id));
		}
		boolean success = delete(ids, null);
		return success;
	}
}